package TwoClientGameConnection;


import java.io.IOException;
import java.io.StringReader;
import java.util.List;
//Outside class
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * Parses a string XML message and constructs a TCGMessage object based on
 * its contents.
 * @author Jace Ferguson
 * @filename TCGMessageReader.java
 */
public class TCGMessageReader{
	/**
	 * Statically create the message based on the XML input string.
	 * @param message	String	XML message
	 * @return	TCGMessage object
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static TCGMessage ParseMessage(String message) throws JDOMException, IOException
	{
		if(message != null)
		{
			SAXBuilder builder = new SAXBuilder();

			//Part of the jdom package.
			Document xmlDoc = builder.build(new StringReader(message));
			Element root = xmlDoc.getRootElement();		
			TCGMessage newMessage;

			newMessage = new TCGMessage(root.getAttribute("id").getValue());
			newMessage.setCommand(root.getChildText("command"));
			newMessage.setMessageType(Integer.getInteger(root.getChildText("type")));

			Element parameters;
			parameters = root.getChild("parameters");
			List<Element> parameterList = parameters.getChildren();
			for(Element parameter : parameterList)
			{
				newMessage.addParameter(parameter.getAttributeValue("ParamName"), parameter.getValue());
			}
			return newMessage;
		}
		else
			throw new IOException("String message is null");
	}
}


